package com.work.flow.common;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class FileTool {

    public static String fileToZip(String sourceFilePath) {
        String fileName = "result.zip";
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        if (!sourceFile.exists()) {
            System.out.println(">>>>>> 待压缩的文件目录：" + sourceFilePath + " 不存在. <<<<<<");
        } else {
            try {
                File zipFile = new File(sourceFilePath + File.separator + fileName);
                if (zipFile.exists()) {
                    System.out.println(">>>>>> " + sourceFilePath + " 目录下存在名字为："
                            + fileName + " 打包文件. <<<<<<");
                    FileTool.deleteFile(sourceFilePath + File.separator + fileName);
                }


                File[] sourceFiles = sourceFile.listFiles();
                if (null == sourceFiles || sourceFiles.length < 1) {
                    System.out.println(">>>>>> 待压缩的文件目录：" + sourceFilePath
                            + " 里面不存在文件,无需压缩. <<<<<<");
                } else {
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024 * 10];
                    for (int i = 0; i < sourceFiles.length; i++) {
                        // 创建ZIP实体,并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                        zos.putNextEntry(zipEntry);
                        // 读取待压缩的文件并写进压缩包里
                        fis = new FileInputStream(sourceFiles[i]);
                        bis = new BufferedInputStream(fis, 1024 * 10);
                        int read = 0;
                        while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                            zos.write(bufs, 0, read);
                        }
                    }
//                    zos.flush();
                    zos.closeEntry();
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                // 关闭流
                try {
                    if (null != bis) {
                        bis.close();
                    }
                    if (null != zos) {
                        zos.close();
                    }
                    if (null != fis) {
                        fis.close();
                    }
                    if (null != zos) {
                        zos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sourceFilePath + File.separator + fileName;
    }
    public static void fileToZip(String sourceFilePath, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = "result.zip";
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            System.out.println(">>>>>> 待压缩的文件目录：" + sourceFilePath + " 不存在. <<<<<<");
        } else {
            ZipOutputStream zos = null;
            BufferedInputStream bis = null;
            try{

                File[] files = sourceFile.listFiles();
                zos = new ZipOutputStream(response.getOutputStream());
                byte[] buf = new byte[8192];
                int len;
                for (int i = 0; i < files.length; i++) {
                    File file = files[i];
                    if (!file.isFile()) continue;
                    ZipEntry ze = new ZipEntry(file.getName());
                    zos.putNextEntry(ze);
                    bis = new BufferedInputStream(new FileInputStream(file));
                    while ((len = bis.read(buf)) > 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                }
                zos.closeEntry();
            }catch(Exception ex){
                ex.printStackTrace();
            }finally {
                if(bis != null){
                    try{
                        bis.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                if(zos != null){
                    try{
                        zos.close();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void unzip(String sZipPathFile) {
        try {
            String sDestPath = new File(sZipPathFile).getParentFile().getAbsolutePath() + File.separator;
            // 先指定压缩档的位置和档名，建立FileInputStream对象
            FileInputStream fins = new FileInputStream(sZipPathFile);
            // 将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(fins);
            ZipEntry ze = null;
            byte[] ch = new byte[256];
            while ((ze = zins.getNextEntry()) != null) {
                File zfile = new File(sDestPath + ze.getName());
                File fpath = new File(zfile.getParentFile().getPath());
                if (ze.isDirectory()) {
                    if (!zfile.exists())
                        zfile.mkdirs();
                    zins.closeEntry();
                } else {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    while ((i = zins.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    zins.closeEntry();
                    fouts.close();
                }
            }
            fins.close();
            zins.close();
            System.err.println("sDestPath" + sDestPath);

        } catch (Exception e) {
            System.err.println("Extract error:" + e.getMessage());
        }
    }

    public static void unzip(String sZipPathFile, String targetPath) {
        try {
            String sDestPath = targetPath;
            // 先指定压缩档的位置和档名，建立FileInputStream对象
            FileInputStream fins = new FileInputStream(sZipPathFile);
            // 将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(fins);
            ZipEntry ze = null;
            byte[] ch = new byte[256];
            while ((ze = zins.getNextEntry()) != null) {
                File zfile = new File(sDestPath + File.separator + ze.getName());
                File fpath = new File(zfile.getParentFile().getPath());
                if (ze.isDirectory()) {
                    if (!zfile.exists())
                        zfile.mkdirs();
                    zins.closeEntry();
                } else {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    while ((i = zins.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    zins.closeEntry();
                    fouts.close();
                }
            }
            fins.close();
            zins.close();
            System.err.println("sDestPath" + sDestPath);

        } catch (Exception e) {
            System.err.println("Extract error:" + e.getMessage());
        }
    }

    /**
     * 删除文件
     *
     * @param path
     */
    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            if (!file.delete()) {
                System.out.println("文件" + path + "删除失败");
            }
        }
    }

    /**
     * 递归删除文件夹路径
     *
     * @param dirPath
     */
    public static void deleteFiles(String dirPath) {
        try {
            File file = new File(dirPath);
            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {
                String[] fileList = file.list();
                for (int i = 0; i < fileList.length; i++) {
                    File delFile = new File(dirPath + File.separator + fileList[i]);
                    if (!delFile.isDirectory()) {
                        delFile.delete();
                    } else if (delFile.isDirectory()) {
                        deleteFiles(dirPath + File.separator + fileList[i]);
                    }
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 找到目录下指定后缀名的文件
     *
     * @param dirPath
     * @return
     */
    public static List<String> findFile(String dirPath, String type) {
        List<String> files = new ArrayList<>();
        File file = new File(dirPath);
        if (file.isDirectory()) {
            String[] fileList = file.list();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].endsWith(type)) {
                    files.add(dirPath + File.separator + fileList[i]);
                }
            }
        }
        return files;
    }

    /**
     * 获取文件名
     *
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath) {
        File file = new File(filePath);
        return file.getName();

    }

    /**
     * 拷贝文件到指定目录
     * @param originPath
     * @param targetPath
     * @return
     */
    public static String copyFileToDir(String originPath, String targetPath) {
        File dir=new File(targetPath);
        if(!dir.exists()||!dir.isDirectory()){
            dir.mkdirs();
        }
        targetPath = targetPath + File.separator + getFileName(originPath);
        File file = new File(originPath);
        File file1 = new File(targetPath);

        System.out.println(file.renameTo(file1));
        return targetPath;
    }
}
